/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.antexpress.dao;

import com.antexpress.pojo.Bill;
import com.antexpress.pojo.BillSelector;
import com.antexpress.pojo.CustomerInfo;
import com.antexpress.pojo.Employee;
import com.antexpress.pojo.ExpressDistribution;
import com.antexpress.pojo.MapCity;
import com.antexpress.pojo.MapDistrict;
import com.antexpress.pojo.MapProvince;
import com.antexpress.pojo.MapTown;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 *
 * @author Dannis
 */
@Repository
public class BillDAOImpl implements BillDAO {

    @Autowired
    private SessionFactory sessionFactory;

    private Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    @Override
    public List<Bill> getAllBill() {
        Session session = getSession();
        Criteria crit = session.createCriteria(Bill.class);
//        crit.add(Restrictions.eq("username", username));
        List<Bill> empList = crit.list();
        return empList;
    }

    @Override
    public boolean addSendBill(Bill newBill) {
        Session session = getSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            session.save(newBill);
            tx.commit();
            session.flush();//spring不能自动提交，所以需要手动刷新
            return true;
        } catch (Exception e) {
            if (tx != null) {
                tx.rollback();
            }
            e.printStackTrace();
            return false;
        } finally {

        }
    }

    @Override
    public List<Bill> getBillByStatus(int status) {
        Session session = getSession();
        Criteria crit = session.createCriteria(Bill.class);
        crit.add(Restrictions.eq("status", status));
        List<Bill> billList = crit.list();
        if (!billList.isEmpty()) {
            return null;
        }

        return billList;
    }

    @Override
    public boolean updateBill(Bill newbill) {
        Session session = getSession();
        boolean isSuccess = false;
        try {
            session.beginTransaction();
            session.save(newbill);
            session.getTransaction().commit();
            isSuccess = true;
            session.flush();
        } catch (Exception e) {
            e.printStackTrace();
            session.getTransaction().rollback();
            isSuccess = false;
        } finally {

        }
        return isSuccess;

    }

    @Override
    public Bill getBillByID(String id) {
        Session session = getSession();
        Criteria crit = session.createCriteria(Bill.class);
        crit.add(Restrictions.eq("id", id));
        List<Bill> billList = crit.list();
        if (billList.isEmpty()) {
            return null;
        }
        Bill bill = billList.get(0);
        return bill;
    }

    @Override
    public boolean deleteBill(Bill bill) {
        Session session = getSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();    //开始一个事务    
            bill.setStatus(-1);
            session.update(bill);             //执行删除    
            tx.commit();                      //提交事务  
            session.flush();//spring不能自动提交，所以需要手动刷新
            return true;
        } catch (Exception e) {
            if (tx != null) {
                tx.rollback();       //事务回滚               
            }
            e.printStackTrace();
            return false;
        } finally {
 
        }
    }

    @Override
    public boolean deleteBills(ArrayList<Bill> bills) {
        Session session = getSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();    //开始一个事务     
            for (int i = 0; i < bills.size(); i++) {
                session.delete(bills.get(i));             //执行删除      
            }
            tx.commit();                      //提交事务  
        } catch (Exception e) {
            if (tx != null) {
                tx.rollback();       //事务回滚               
            }
            e.printStackTrace();
            return false;
        } finally {

        }
        return true;
    }

    @Override
    public List<Bill> selectBill(BillSelector select) {
        Session session = getSession();
        Transaction tx = null;
        Criteria crit = session.createCriteria(Bill.class);
//        if (select.isChoose_createtime()) {
            crit.add(Restrictions.between("createtime", select.getStartcreatetime(), select.getEndcreatetime()));
//        }
//        if (select.isChoose_status()) {
            crit.add(Restrictions.eq("status", select.getStatus()));
//        }
//        if (select.isChoose_updatetime()) {
            crit.add(Restrictions.between("updatetime", select.getStartupdatetime(), select.getEndupdatetime()));
//        }
//        if (select.isChoose_start_freight() && !(select.isChoose_end_freight())) {//选择大于最小值，未设置最大值
//            crit.add(Restrictions.ge("freight", select.getStartfreight()));//大于等于最小值
//        }
//        if (select.isChoose_end_freight() && !(select.isChoose_start_freight())) {
//            crit.add(Restrictions.le("freight", select.getEndfreight()));//小于等于最大值
//        }
//        if (select.isChoose_end_freight() && select.isChoose_start_freight()) {//between
            crit.add(Restrictions.between("freight", select.getStartfreight(), select.getEndfreight()));
//        }
//        if (select.isChoose_start_weight() && !(select.isChoose_end_weight())) {//选择大于最小值，未设置最大值
//            crit.add(Restrictions.between("weight", select.getStartweight(),select.getEndweight()));//大于等于最小值
//        }
//        if (select.isChoose_end_weight() && !(select.isChoose_start_weight())) {
//            crit.add(Restrictions.le("weight", select.getEndweight()));//小于等于最大值
//        }
//        if (select.isChoose_start_weight() && select.isChoose_end_weight()) {//between
            crit.add(Restrictions.between("weight", select.getStartweight(), select.getEndweight()));
//        }
        List<Bill> billList = crit.list();

//        List<Bill> newbillList = new ArrayList<Bill>();

//        if (select.isChoose_start_province()) {
//            for (int i = 0; i < billList.size(); i++) {
//                if (billList.get(i).getConsigneeInfo().getMapTown().getMapDistrict().getMapCity().
//                        getMapProvince().getId().equals(select.getStartprovince())) {
//                    newbillList.add(billList.get(i));
//                }
//            }
//        }
//        if (select.isChoose_end_province()) {//未完成
//            for (int i = 0; i < billList.size(); i++) {
//                if (billList.get(i).getConsignorInfo().getMapTown().getMapDistrict().getMapCity().
//                        getMapProvince().getId().equals(select.getEndprovince())) {
//                    newbillList.add(billList.get(i));
//                }
//            }
//        }
//        if (select.isChoose_start_city()) {//未完成
//            for (int i = 0; i < billList.size(); i++) {
//                if (billList.get(i).getConsigneeInfo().getMapTown().getMapDistrict().getMapCity()
//                        .getId().equals(select.getStartcity())) {
//                    newbillList.add(billList.get(i));
//                }
//            }
//        }
//
//        if (select.isChoose_end_city()) {//未完成
//            for (int i = 0; i < billList.size(); i++) {
//                if (billList.get(i).getConsignorInfo().getMapTown().getMapDistrict().getMapCity()
//                        .getId().equals(select.getEndcity())) {
//                    newbillList.add(billList.get(i));
//                }
//            }
//        }
//        if (select.isChoose_pro_city_select()) {
//            List<Bill> newbillList2 = new ArrayList<Bill>();
//            List<String> billidS = new ArrayList<String>();
//            for (int i = 0; i < newbillList.size(); i++) {//去重
//                if (!billidS.contains(newbillList.get(i).getId())) {
//                    billidS.add(newbillList.get(i).getId());
//                    newbillList2.add(newbillList.get(i));
//                }
//            }
//            return newbillList2;
//        }
        if (billList.isEmpty()) {
            return null;
        }
        return billList;
    }

    @Override
    public List<MapProvince> getAllProvince() {
        Session session = getSession();
        Criteria crit = session.createCriteria(MapProvince.class);
        List<MapProvince> provincelist = crit.list();
        return provincelist;
    }

    @Override
    public List<MapCity> getAllCityByProID(String proID) {
        Session session = getSession();
        Criteria crit = session.createCriteria(MapCity.class);
        MapProvince province = getProvinceByID(proID);
        crit.add(Restrictions.eq("mapProvince", province));
        List<MapCity> citylist = crit.list();
        return citylist;
    }

    @Override
    public List<MapDistrict> getAllDistrictByCityId(String cityID) {
        Session session = getSession();
        Criteria crit = session.createCriteria(MapDistrict.class);
        MapCity city = getCityByID(cityID);
        crit.add(Restrictions.eq("mapCity", city));
        List<MapDistrict> list = crit.list();
        return list;
    }

    @Override
    public List<MapTown> getAllTownByDistrictID(String districtID) {
        Session session = getSession();
        Criteria crit = session.createCriteria(MapTown.class);
        MapDistrict district = getDistrictByID(districtID);
        crit.add(Restrictions.eq("mapDistrict", district));
        List<MapTown> list = crit.list();
        return list;
    }

    @Override
    public MapProvince getProvinceByID(String id) {
        Session session = getSession();
        Criteria crit = session.createCriteria(MapProvince.class);
        crit.add(Restrictions.eq("id", id));
        List<MapProvince> list = crit.list();
        if (list.isEmpty()) {
            return null;
        }
        System.out.println("111111111111111111111111111111111111111111111" + list.get(0).getName());
        return list.get(0);
    }

    @Override
    public MapCity getCityByID(String id) {
        Session session = getSession();
        Criteria crit = session.createCriteria(MapCity.class);
        crit.add(Restrictions.eq("id", id));
        List<MapCity> list = crit.list();
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    @Override
    public MapDistrict getDistrictByID(String id) {
        Session session = getSession();
        Criteria crit = session.createCriteria(MapDistrict.class);
        crit.add(Restrictions.eq("id", id));
        List<MapDistrict> list = crit.list();
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    @Override
    public MapTown getTownByID(String id) {
        Session session = getSession();
        Criteria crit = session.createCriteria(MapTown.class);
        crit.add(Restrictions.eq("id", id));
        List<MapTown> list = crit.list();
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    @Override//辅助创造Bill 先把Customer存入
    public void saveCustomerInfo(CustomerInfo consignorinfo) {
        Session session = getSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            session.save(consignorinfo);
            tx.commit();
            session.flush();//spring不能自动提交，所以需要手动刷新
        } catch (Exception e) {
            if (tx != null) {
                tx.rollback();
            }
            e.printStackTrace();
        } finally {
           
        }
    }

    @Override
    public int getAllRowCount() {
        Session session = getSession();
        Criteria crit = session.createCriteria(Bill.class);
        crit.setProjection(Projections.rowCount());
        Long count = (Long) crit.uniqueResult();
        return count.intValue();
    }

    @Override
    public List<Bill> listBillForPage(int offset, int length, int status) {
        Session session = getSession();
        Criteria crit = session.createCriteria(Bill.class);
        crit.setFirstResult(offset);//表格分页开始位置
        crit.setMaxResults(length);//表格根据多少个一组进行分页
        crit.add(Restrictions.eq("status", status));
        crit.addOrder(Order.desc("createtime"));
        List<Bill> billList = crit.list();
        return billList;
    }

    //通过emp查找所属区域
    @Override
    public MapTown getEmployeeMapTown(Employee emp) {
        Session session = getSession();
        Criteria crit = session.createCriteria(ExpressDistribution.class);
        crit.add(Restrictions.eq("employee", emp));
        List<ExpressDistribution> list = crit.list();
        if (!list.isEmpty()) {
            MapTown town = list.get(0).getmapTown();
            return town;
        }
        if (list.isEmpty()) {
            return null;
        }
        return null;

    }

    //查询相应区域的管理员的业务单
    @Override
    public List<Bill> listNormalBillForPage(int offset, int length, int status, List<CustomerInfo> consignorinfo) {
        Session session = getSession();
        List<Bill> lastlist = new ArrayList<>();
        for (int i = 0; i < consignorinfo.size(); i++) {
            Criteria crit = session.createCriteria(Bill.class);
            crit.add(Restrictions.eq("consignorInfo", consignorinfo.get(i)));
            crit.add(Restrictions.eq("status", 1));
            List<Bill> list = crit.list();
            if (!list.isEmpty()) {
                for (int j = 0; j < list.size(); j++) {
                    lastlist.add(list.get(j));
                }
            }
        }
        if (lastlist.isEmpty()) {
            return null;
        }
        return lastlist;
    }

    @Override
    public List<CustomerInfo> getCustomerListInfoByMapTown(MapTown town) {
        Session session = getSession();
        Criteria crit = session.createCriteria(CustomerInfo.class);
        crit.add(Restrictions.eq("mapTown", town));
        List<CustomerInfo> list = crit.list();
        if (list.isEmpty()) {
            return null;
        }
        return list;
    }

    @Override
    public List<Bill> listNormalBillForPage(int offset, int length, int status, List<CustomerInfo> consignorinfo, Date createtimestart, Date createtimeend, Date updatetimestart, Date updatetimeend) {
        Session session = getSession();
        List<Bill> lastlist = new ArrayList<>();
        for (int i = 0; i < consignorinfo.size(); i++) {
            Criteria crit = session.createCriteria(Bill.class);
            crit.add(Restrictions.eq("consignorInfo", consignorinfo.get(i)));
            crit.add(Restrictions.eq("status", 1));
            crit.add(Restrictions.between("createtime", createtimestart, createtimeend));
            crit.add(Restrictions.between("updatetime", updatetimestart, updatetimeend));
            List<Bill> list = crit.list();
            if (!list.isEmpty()) {
                for (int j = 0; j < list.size(); j++) {
                    lastlist.add(list.get(j));
                }
            }
        }
        if (lastlist.isEmpty()) {
            return null;
        }
        return lastlist;
    }

    @Override
    public int getNumOfFinishedBill() {
        int num = 0;
        Session session = getSession();
        Criteria crit = session.createCriteria(Bill.class);
        crit.add(Restrictions.eq("status", 4));
        List<CustomerInfo> list = crit.list();
        num = list.size();
        if (list.isEmpty()) {
            return 0;
        }
        return num;
    }

    @Override
    public int getNumOfNotFinishedBill() {
        int num = 0;
        Session session = getSession();
        Criteria crit = session.createCriteria(Bill.class);
        crit.add(Restrictions.ne("status", 4));
        List<CustomerInfo> list = crit.list();
        num = list.size();
        if (list.isEmpty()) {
            return 0;
        }
        return num;
    }

}
